package com.vpx.server.controller.system;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.IdUtil;

import cn.hutool.json.JSONObject;
import com.vpx.server.bean.entity.BaseInfo;
import com.vpx.server.bean.entity.CProjectFlowInstance;
import com.vpx.server.bean.entity.CTypeRel;
import com.vpx.server.bean.order.project.CProjectFlowInstanceOrder;
import com.vpx.server.bean.order.system.BaseInfoOrder;
import com.vpx.server.bean.order.system.ProjectConfigPageOrder;
import com.vpx.server.bean.result.system.ProjectConfigResult;
import com.vpx.server.framework.base.BasePageResult;
import com.vpx.server.framework.base.ResultMsg;
import com.vpx.server.framework.utils.DateUtils;
import com.vpx.server.service.system.*;
import com.vpx.server.utils.UserLoginUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/api/cprojectflowinstance")
@Api(tags ="测试用例")
public class CProjectFlowInstanceController {
    @Autowired
    private CProjectFlowInstanceService service;
    @Autowired
    private CTypeRelService typeRelService;

    @Autowired
    private BaseInfoService baseInfoService;
    @Resource
    SqlService sqlService;

    @Resource
    SqlExtService sqlExtService;

    @ApiOperation("添加")
    @PostMapping(value ="/insert")
    public ResultMsg insert(@RequestBody  CProjectFlowInstance c){
        if(validate(c)) {
            return  ResultMsg.fail("名称重复!");
        }
        c.setId(IdUtil.getSnowflakeNextIdStr());
        Date date = DateUtil.date(System.currentTimeMillis());
        c.setCreateTime(date.toString());
        c.setInstanceContent("");
        service.insert(c);
        //保存分类关联数据
        CTypeRel obj = new CTypeRel();
        obj.setId(IdUtil.simpleUUID());
        obj.setCreateTime(date.toString());
        obj.setTransactionId(c.getId());
        obj.setTypeId(c.getTypeId());
        BaseInfoOrder order = new BaseInfoOrder();
        order.setId(c.getId());
        if("1".equals(c.getBusType())) {
            //分支
            obj.setCode("1");
            order.setType("2");
            order.setTemplateId("1e2ac3227f7c2bc959138e0974f5dc94");
            //当前节点类型node_type(1测试用例2流程步8分支)
            order.setNodeType("8");
        } else {
            obj.setCode("2");
            order.setType("1");
            //用例模版
            order.setTemplateId("254081f422f94978645111951a65e9f4");
            order.setNodeType("1");
            //用例插入用例业务类型数据
            Map<String,Object> ywMap = new HashMap<>();
            ywMap.put("id", c.getId());
            ywMap.put("yw_id", c.getYwTypeId());
            ywMap.put("yl_id", c.getId());
            this.sqlService.execute("30" , ywMap);
        }
        order.setInstanceContent("");
        order.setTypeCode(c.getTypeId());
        typeRelService.insert(obj);
        order.setName(c.getInstanceName());
        order.setIcon("kxgc");
        order.setNum(IdUtil.getSnowflakeNextIdStr());
        order.setNodeMethod("1");
        order.setNotes("false");
        baseInfoService.saveBaseInfo(order);


        //用例或者分支 基础测试项属性表(c_base_info_attr)
        Map<String,Object> map = new HashMap<>();
        map.put("id",IdUtil.getSnowflakeNextIdStr());
        map.put("base_info_id",order.getId());
        map.put("template_id", order.getTemplateId());
        map.put("type_code",c.getTypeId());
        map.put("create_user", UserLoginUtils.getCurrentUser() == null ? "admin" : UserLoginUtils.getCurrentUser().getId().toString());
        map.put("create_time", DateUtils.getDateTimeStr());
        this.sqlService.execute("5" , map);
        return ResultMsg.success("");
    }
    @ApiOperation("删除")
    @GetMapping("/delete")
    public ResultMsg delete(CProjectFlowInstance c){
        service.delete(c);
        //删除c_base_info_attr 数据
        this.sqlExtService.execute("delete from c_base_info_attr where base_info_id in (select id from c_base_info where id = '"+c.getId()+"' or parent_all_id like '%"+c.getId()+"%')");
        //c_base_info
        this.sqlExtService.execute("delete from c_base_info where id = '"+c.getId()+"' or  parent_all_id like '%"+c.getId()+"%'");

        //删除关联表
        sqlExtService.execute("delete from c_type_rel where transaction_id = '"+c.getId()+"'");

        sqlExtService.execute("delete from c_yw where yl_id = '"+c.getId()+"'");
        return ResultMsg.success("");
    }
    @ApiOperation("修改")
    @PostMapping("/update")
    public ResultMsg update(@RequestBody CProjectFlowInstance c){
        if(validate(c)) {
            return  ResultMsg.fail("名称重复!");
        }
        service.update(c);
        BaseInfo info = baseInfoService.getById(c.getId());
        info.setName(c.getInstanceName());
        baseInfoService.updateById(info);
        if("2".equals(c.getBusType())) {
            //用例插入用例业务类型数据
            Map<String,Object> ywMap = new HashMap<>();
            ywMap.put("id", c.getId());
            ywMap.put("yw_id", c.getYwTypeId());
            ywMap.put("yl_id", c.getId());
            sqlExtService.execute("delete from c_yw where yl_id = '"+c.getId()+"'");
            this.sqlService.execute("30" , ywMap);
        }

        return ResultMsg.success("成功");
    }
    private boolean validate(CProjectFlowInstance obj) {
        boolean flag = false;
        String name = obj.getInstanceName();
        String sql = "select count(1) num from c_project_flow_instance where instance_name = '"+name+"'";
        if(StringUtils.isNotBlank(obj.getId())) {
            sql = sql + " and id &lt;&gt; '" + obj.getId() + "'";
        }
        int num = sqlExtService.findOne(sql, Integer.class);
        if (num > 0) {
            flag = true;
        }
        return  flag;
    }
    @ApiOperation("查询")
    @GetMapping("/selectAll")
    public ResultMsg selectAll(){
        List<CProjectFlowInstance> list=
                service.selectAll();
        return ResultMsg.success(list);
    }

    @ApiOperation("测试用例详情")
    @GetMapping("/detail")
    public ResultMsg detail(CProjectFlowInstance c){
        CProjectFlowInstance obj= service.getById(c.getId());
        return ResultMsg.success(obj);
    }

    @GetMapping("/pageQuery")
    @ApiOperation("分页查询")
    //@RequestAuth(poicy = AuthPoicy.AUTH)
    public ResultMsg<BasePageResult<CProjectFlowInstance>> pageQuery(CProjectFlowInstanceOrder order) {

        return ResultMsg.success(service.page(order));
    }

    @ApiOperation("查询业务类型")
    @GetMapping("/ywTree")
    public ResultMsg ywTree() {
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        treeNodeConfig.setIdKey("id");
        treeNodeConfig.setNameKey("name");
        treeNodeConfig.setParentIdKey("parent_id");
        List<JSONObject> list = sqlExtService.findListObject("select id,name,parent_id from c_yw_info", JSONObject.class);
        String rootId = "0";
        List<Tree<String>> treeNodes = TreeUtil.build(list, rootId, treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getStr("id"));
                    tree.setName(treeNode.getStr("name"));
                    tree.setParentId(treeNode.getStr("parent_id"));
                });
        return ResultMsg.success(treeNodes);
    }
}
